package cn.iocoder.yudao.module.reading.controller.app.assignment;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
import cn.iocoder.yudao.module.reading.controller.app.assignment.vo.*;
import cn.iocoder.yudao.module.reading.controller.app.classes.vo.ClassRespVO;
import cn.iocoder.yudao.module.reading.service.assignment.AssignmentService;
import cn.iocoder.yudao.module.reading.service.classes.ClassService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户 APP - 作业管理
 *
 * @author 芋道源码
 */
@Tag(name = "用户 APP - 作业管理")
@RestController("readingAssignmentController")
@RequestMapping("/reading/assignments")
@Validated
@Slf4j
public class AssignmentController {

    @Resource
    private AssignmentService assignmentService;
    @Resource
    private ClassService classService;

    @PostMapping("")
    @Operation(summary = "创建作业")
    @PreAuthenticated
    public CommonResult<Long> createAssignment(@Valid @RequestBody AssignmentCreateReqVO createReqVO) {
        Long userId = getLoginUserId();
        log.info("创建作业，用户ID: {}, 请求参数: {}", userId, createReqVO);

        // 验证班级ID参数
        if (createReqVO.getClassId() == null && (createReqVO.getClassIds() == null || createReqVO.getClassIds().isEmpty())) {
            throw ServiceExceptionUtil.exception(BAD_REQUEST, "班级ID不能为空");
        }

        // 如果指定了多个班级，使用跨班级创建方法
        if (createReqVO.getClassIds() != null && createReqVO.getClassIds().size() > 1) {
            List<Long> assignmentIds = assignmentService.createMultiClassAssignment(userId, createReqVO);
            // 返回第一个作业ID（兼容现有接口）
            return success(assignmentIds.get(0));
        }

        Long assignmentId = assignmentService.createAssignment(userId, createReqVO);
        return success(assignmentId);
    }

    @PostMapping("/multi-class")
    @Operation(summary = "创建跨班级作业")
    @PreAuthenticated
    public CommonResult<List<Long>> createMultiClassAssignment(@Valid @RequestBody AssignmentCreateReqVO createReqVO) {
        Long userId = getLoginUserId();
        log.info("创建跨班级作业，用户ID: {}, 请求参数: {}", userId, createReqVO);

        // 验证班级ID列表不能为空
        if (createReqVO.getClassIds() == null || createReqVO.getClassIds().isEmpty()) {
            throw ServiceExceptionUtil.exception(BAD_REQUEST, "班级ID不能为空");
        }

        List<Long> assignmentIds = assignmentService.createMultiClassAssignment(userId, createReqVO);
        return success(assignmentIds);
    }

    @GetMapping("/{assignmentId}")
    @Operation(summary = "获取作业详情")
    @PreAuthenticated
    public CommonResult<AssignmentRespVO> getAssignmentDetail(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId) {
        Long userId = getLoginUserId();
        log.info("获取作业详情，作业ID: {}, 用户ID: {}", assignmentId, userId);

        AssignmentRespVO result = assignmentService.getAssignmentDetail(assignmentId, userId);
        return success(result);
    }

    @PutMapping("/{assignmentId}")
    @Operation(summary = "修改作业")
    @PreAuthenticated
    public CommonResult<String> updateAssignment(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId,
            @Valid @RequestBody AssignmentUpdateReqVO updateReqVO) {
        Long userId = getLoginUserId();
        log.info("修改作业，作业ID: {}, 用户ID: {}, 请求参数: {}", assignmentId, userId, updateReqVO);

        assignmentService.updateAssignment(assignmentId, userId, updateReqVO);
        return success("作业修改成功");
    }

    @DeleteMapping("/{assignmentId}")
    @Operation(summary = "删除作业")
    @PreAuthenticated
    public CommonResult<String> deleteAssignment(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId) {
        Long userId = getLoginUserId();
        log.info("删除作业，作业ID: {}, 用户ID: {}", assignmentId, userId);

        assignmentService.deleteAssignment(assignmentId, userId);
        return success("作业删除成功");
    }

    @GetMapping("/{assignmentId}/stats")
    @Operation(summary = "获取作业完成统计")
    @PreAuthenticated
    public CommonResult<AssignmentStatsRespVO> getAssignmentStats(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId) {
        Long userId = getLoginUserId();
        log.info("获取作业完成统计，作业ID: {}, 用户ID: {}", assignmentId, userId);

        AssignmentStatsRespVO result = assignmentService.getAssignmentStats(assignmentId, userId);
        return success(result);
    }

    @GetMapping("/{assignmentId}/completions")
    @Operation(summary = "获取作业完成情况")
    @PreAuthenticated
    public CommonResult<List<AssignmentCompletionRespVO>> getAssignmentCompletions(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId) {
        Long userId = getLoginUserId();
        log.info("获取作业完成情况，作业ID: {}, 用户ID: {}", assignmentId, userId);

        List<AssignmentCompletionRespVO> result = assignmentService.getAssignmentCompletions(assignmentId, userId);
        return success(result);
    }

    @PostMapping("/{assignmentId}/complete")
    @Operation(summary = "提交作业完成记录")
    @PreAuthenticated
    public CommonResult<String> completeAssignment(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId,
            @Valid @RequestBody AssignmentCompleteReqVO completeReqVO) {
        Long userId = getLoginUserId();
        log.info("提交作业完成记录，作业ID: {}, 用户ID: {}, 请求参数: {}", assignmentId, userId, completeReqVO);

        assignmentService.completeAssignment(assignmentId, userId, completeReqVO);
        return success("作业提交成功");
    }

    @GetMapping("/{assignmentId}/classes")
    @Operation(summary = "获取作业关联的班级列表")
    @PreAuthenticated
    public CommonResult<List<AssignmentClassRespVO>> getAssignmentClasses(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId) {
        Long userId = getLoginUserId();
        log.info("获取作业关联班级，作业ID: {}, 用户ID: {}", assignmentId, userId);

        List<AssignmentClassRespVO> classes = assignmentService.getAssignmentClasses(assignmentId, userId);
        return success(classes);
    }

    @GetMapping("/books/selectable")
    @Operation(summary = "获取可选绘本列表")
    @PreAuthenticated
    public CommonResult<List<SelectableBookRespVO>> getSelectableBooks(
            @Parameter(description = "语言类型", example = "english") @RequestParam(value = "language", required = false, defaultValue = "english") String language) {
        Long userId = getLoginUserId();
        log.info("获取可选绘本列表，用户ID: {}, 语言: {}", userId, language);

        List<SelectableBookRespVO> result = assignmentService.getSelectableBooks(language);
        return success(result);
    }

    @GetMapping("/book-sets")
    @Operation(summary = "获取绘本集列表")
    @PreAuthenticated
    public CommonResult<List<BookSetSelectableRespVO>> getSelectableBookSets(
            @Parameter(description = "语言类型", example = "english") @RequestParam(value = "language", required = false) String language) {
        Long userId = getLoginUserId();
        log.info("获取绘本集列表，用户ID: {}, 语言: {}", userId, language);

        List<BookSetSelectableRespVO> result = assignmentService.getSelectableBookSets(language);
        return success(result);
    }

    @GetMapping("/book-sets/{bookSetId}/books")
    @Operation(summary = "获取绘本集内的绘本列表")
    @PreAuthenticated
    public CommonResult<List<SelectableBookRespVO>> getBooksByBookSetId(
            @Parameter(description = "绘本集ID", required = true) @PathVariable Long bookSetId) {
        Long userId = getLoginUserId();
        log.info("获取绘本集内绘本列表，用户ID: {}, 绘本集ID: {}", userId, bookSetId);

        List<SelectableBookRespVO> result = assignmentService.getBooksByBookSetId(bookSetId);
        return success(result);
    }

    @GetMapping("/classes/managed")
    @Operation(summary = "获取用户管理的班级")
    @PreAuthenticated
    public CommonResult<List<ClassRespVO>> getManagedClasses() {
        Long userId = getLoginUserId();
        log.info("获取用户管理的班级，用户ID: {}", userId);

        // 获取用户创建的班级
        List<ClassRespVO> result = classService.getUserClasses(userId).stream()
                .filter(c -> "teacher".equals(c.getRole()))
                .collect(Collectors.toList());
        return success(result);
    }

    // =============================================
    // 作业未完成情况管理接口
    // =============================================

    @GetMapping("/{assignmentId}/incomplete-students")
    @Operation(summary = "获取作业未完成的学生列表")
    @PreAuthenticated
    public CommonResult<List<IncompleteStudentRespVO>> getIncompleteStudents(
            @Parameter(description = "作业ID", required = true, example = "1") @PathVariable("assignmentId") Long assignmentId) {
        Long userId = getLoginUserId();
        log.info("获取作业未完成的学生列表，作业ID: {}, 用户ID: {}", assignmentId, userId);

        List<IncompleteStudentRespVO> result = assignmentService.getIncompleteStudents(assignmentId, userId);
        return success(result);
    }

    @GetMapping("/classes/{classId}/incomplete-assignments")
    @Operation(summary = "获取学生的未完成作业列表")
    @PreAuthenticated
    public CommonResult<List<IncompleteAssignmentRespVO>> getStudentIncompleteAssignments(
            @Parameter(description = "班级ID", required = true, example = "1") @PathVariable("classId") Long classId) {
        Long userId = getLoginUserId();
        log.info("获取学生的未完成作业列表，班级ID: {}, 用户ID: {}", classId, userId);

        List<IncompleteAssignmentRespVO> result = assignmentService.getStudentIncompleteAssignments(classId, userId);
        return success(result);
    }

    @GetMapping("/classes/{classId}/summary")
    @Operation(summary = "获取班级作业汇总统计")
    @PreAuthenticated
    public CommonResult<ClassAssignmentSummaryRespVO> getClassAssignmentSummary(
            @Parameter(description = "班级ID", required = true, example = "1") @PathVariable("classId") Long classId) {
        Long userId = getLoginUserId();
        log.info("获取班级作业汇总统计，班级ID: {}, 用户ID: {}", classId, userId);

        ClassAssignmentSummaryRespVO result = assignmentService.getClassAssignmentSummary(classId, userId);
        return success(result);
    }

    @GetMapping("/classes/{classId}/overdue")
    @Operation(summary = "获取班级逾期作业列表")
    @PreAuthenticated
    public CommonResult<List<AssignmentRespVO>> getOverdueAssignments(
            @Parameter(description = "班级ID", required = true, example = "1") @PathVariable("classId") Long classId) {
        Long userId = getLoginUserId();
        log.info("获取班级逾期作业列表，班级ID: {}, 用户ID: {}", classId, userId);

        List<AssignmentRespVO> result = assignmentService.getOverdueAssignments(classId, userId);
        return success(result);
    }

}
